﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Shsc.Net.Common.Dto;
using Shsc.Net.Common.Validator;

namespace Shsc.Net.Web.Extension
{
    public class ValidatorAttribute : ActionFilterAttribute
    {
        public String Key { get; set; }

        public ValidatorAttribute()
        {
        }

        public ValidatorAttribute(string key)
        {
            Key = key;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string key = string.IsNullOrEmpty(Key) ? "dto" : Key;
            BaseDto dto = null;
            if (filterContext.ActionParameters.ContainsKey(key))
            {
                dto = (BaseDto)filterContext.ActionParameters[key];
            }

            ValidatorResultList lisValidatorResult = new ValidatorResultList();

            string language = filterContext.HttpContext.Request.ServerVariables["Http_Accept_Language"];
            if (language.IndexOf(",") > 0)
            {
                language = language.Substring(0, language.IndexOf(","));
            }
            dto.Language = language;

            Validator.DoValidator(dto, lisValidatorResult);
            dto.DoValidator(lisValidatorResult);
            ModelStateDictionary ModelState = filterContext.Controller.ViewData.ModelState;
            if (lisValidatorResult.Count > 0)
            {
                for (int i = 0; i < lisValidatorResult.Count; i++ )
                {
                    ModelState.AddModelError(lisValidatorResult[i].CtrlId, lisValidatorResult[i].MessageContent);
                }
                filterContext.Result = new ViewResult();
                filterContext.Controller.ViewData.Model = dto;
            }
            else
            {
                base.OnActionExecuting(filterContext);
            }
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
        }
    }
}
